﻿using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Light))]
public class Firestick:MonoBehaviour {

  public float IgnitePrePeakDuration = 0.3f;
  public float IgnitePeakLightIntensity = 8.0f;
  public float IgnitePostPeakDuration = 0.5f;
  public float MaxLightIntensity = 1.0f;
  public float AttenuationDuration = 3.0f;
  public float NoiseAmplitude = 0.1f;

  public float TestIgniteTime = 5.0f;

  private float remainLifetime = 0.0f;
  private float igniteLifetime = 0.0f;
  private FirestickState state = FirestickState.Unlight;

  private enum FirestickState {
    Unlight = 0,
    IgnitePrePeak,
    IgnitePostPeak,
    Lighting
  };

  // Use this for initialization
  void Start () {

  }

  // Update is called once per frame
  void Update () {
    if (state == FirestickState.IgnitePrePeak) {
      light.intensity = IgnitePeakLightIntensity * igniteLifetime
          / IgnitePrePeakDuration;
      igniteLifetime += Time.deltaTime;
      if (igniteLifetime > IgnitePrePeakDuration) {
        igniteLifetime -= IgnitePrePeakDuration;
        state = FirestickState.IgnitePostPeak;
      }
    }
    else if (state == FirestickState.IgnitePostPeak) {   // post
      light.intensity = MaxLightIntensity
          + (IgnitePeakLightIntensity - MaxLightIntensity)
              * (1.0f - igniteLifetime / IgnitePostPeakDuration);
      igniteLifetime += Time.deltaTime;
      if (igniteLifetime > IgnitePostPeakDuration) {
        state = FirestickState.Lighting;
      }
    }
    else if (state == FirestickState.Lighting) {  // normal
      float noise = NoiseAmplitude * Random.value;
      float baseLight = MaxLightIntensity;
      if (remainLifetime < AttenuationDuration) {
        baseLight = MaxLightIntensity * remainLifetime / AttenuationDuration;
      }
      light.intensity = baseLight + noise;

      remainLifetime -= Time.deltaTime;
      if (remainLifetime < 0.0f) {
        light.enabled = false;
        state = FirestickState.Unlight;
      }
    }
    // debug
    if (remainLifetime < 0.001f) {
      if (Input.GetKeyDown(KeyCode.Q)) {
        Ignite(TestIgniteTime);
      }
    }
  }

  public void Ignite (float time) {
    remainLifetime = time;
    light.enabled = true;
    state = FirestickState.IgnitePrePeak;
    igniteLifetime = 0.0f;
  }
}
